<?php


namespace App\Service\Store;


use App\Constants\Goods;
use App\Dao\GoodsCategoryDao;
use App\Dao\GoodsContentDao;
use App\Dao\GoodsDao;
use App\Dao\GoodsPropertyDao;
use App\Dao\GoodsPropertyValueDao;
use App\Dao\GoodsSkuDao;
use App\Exception\BusinessException;
use App\Exception\CustomException;
use App\Service\Service;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

/**
 * 商品服务
 * @author 陈奕文
 * @package App\Service\Store
 */
class GoodsService extends Service
{

    /**
     * 商品Dao
     * @Inject()
     * @var GoodsDao
     */
    public $dao;

    /**
     * 商品种类Dao
     * @Inject()
     * @var GoodsCategoryDao
     */
    public $goods_category_dao;

    /**
     * 商品内容Dao
     * @Inject()
     * @var GoodsContentDao
     */
    public $goods_contents_dao;


    /**
     * 商品SkuDao
     * @Inject()
     * @var GoodsSkuDao
     */
    public $goods_sku_dao;


    /**
     * 商品属性Dao
     * @Inject()
     * @var GoodsPropertyDao
     */
    public $goods_property_dao;


    /**
     * 商品属性值Dao
     * @Inject()
     * @var GoodsPropertyValueDao
     */
    public $goods_ppy_values_dao;


    /**
     * 获取商品列表
     * @param array $params
     * @return array
     */
    public function getGoodsList(array $params)
    {
        $map = [];

        isset($params['id']) && !empty($params['id']) && $map['id'] = ['like',"%{$params['id']}%"]; // 商品ID
        isset($params['title']) && !empty($params['title']) && $map['title'] = ['like',"%{$params['title']}%"]; // 商品标题
//        $select = ['id', 'category_id', 'title', 'price', 'original_price',
//            'integral', 'picture', 'sort', 'stock', 'disable', 'created_at',
//            'page_id', 'sales', 'view_num', 'caption', 'buy_type', 'banners', 'external_url', 'store_clause', 'industry'];


        $select = ['id', 'category_id', 'title', 'price', 'original_price',
            'integral', 'picture', 'sort', 'stock', 'disable'];
        $sort = 'sort desc';

        // 分页
        $page_size = null;
        if (isset($params['page'])) {
            $page_size = 10;
            isset($params['page_size']) && !empty($page_size) && $page_size = (int)$params['page_size'];
        }

        $goods_list = $this->dao->getGoodsByMap($map, $sort, $select, $page_size)->toArray();
        if (isset($goods_list['data'])) {
            $goods_list['data'] = $this->joinGoodsRelatedData($goods_list['data']);
        } else {
            $goods_list = $this->joinGoodsRelatedData($goods_list);
        }
        return $goods_list;
    }

    /**
     * 拼接关联数据
     * @param array $goods_list
     * @return array
     */
    public function joinGoodsRelatedData(array $goods_list)
    {
        $cate_ids = array_unique(array_column($goods_list, 'category_id'));
        $cats = $this->goods_category_dao->getCategoriesByIds($cate_ids);
        $category_names = $cats->pluck('name', 'id')->toArray();

        foreach ($goods_list as $key => $item) {
            $goods_list[$key]['category_name'] = $category_names[$item['category_id']]??""; // 分类名称
            $goods_list[$key]['status_text'] = Goods::DISABLE_LIST[$item['disable']] ??""; // 状态(中文)
        }

        return $goods_list;
    }

    /**
     * 获得商品通过ID
     * @param int $id
     * @return mixed
     */
    public function getGoodsInfoById(int $id)
    {
        $select = ['id', 'category_id', 'title', 'price', 'original_price',
            'integral', 'picture', 'sort', 'stock', 'disable', 'created_at',
            'page_id', 'sales', 'view_num', 'caption', 'buy_type', 'banners', 'external_url', 'store_clause', 'industry'];
        $goods = $this->dao->getGoodsSelectById($id, $select)->toArray();
        $content = $this->goods_contents_dao->getGoodsContentByGoodsId($id)->toArray();
        $goods['create_time'] = date("Y-m-d H:i:s", (int)$goods['created_at']); // 创建时间
        $goods['content'] = $content['content']; // 内容
        $goods['weight'] = $content['weight']; // 净重
        $goods['tag'] = $content['tag']; // 标签
        $goods['unit'] = $content['unit']; // 计量单位
        $top_categories = $this->goods_category_dao->getTopCategory()->pluck('name', 'id')->toArray();
        $cate_ids = array_keys($top_categories);
        $categories = $this->goods_category_dao->getSuperCategoriesByIds($cate_ids)->toArray();

        foreach ($categories as &$category) {
            $category['name'] = $top_categories[$category['pid']]."--".$category['name']; // 所属分类
        }

        $goods['categories'] = $categories;
       return $goods;
    }

    /**
     * 商品数据编辑
     * @param array $params
     */
    public function editData(array $params)
    {
        if(!isset($params['id'])) throw new BusinessException(403, "请输入传递商品ID");
        $id = (int)$params['id'];
        $goods_data = [];
        // 保存Goods表
        $goods_data['category_id'] = (int)$params['category_id']; // 种类ID
        $goods_data['title'] = $params['title']; // 商品标题
        $goods_data['buy_type'] = (int)$params['buy_type']; // 购买方式
        $goods_data['picture'] = $params['picture']; // 封面图
        isset($params['banners']) && $goods_data['banners'] = json_encode($params['banners']); // 轮播图
        $goods_data['price'] = (float)$params['price']; // 商品价格
        $goods_data['original_price'] = (float)$params['original_price']; // 商品原价
        $goods_data['integral'] = (int)$params['integral']; // 积分
        isset($params['sort']) && $goods_data['sort'] = (int)$params['sort']; // 排序
        isset($params['page_id']) && $goods_data['page_id'] = (int)$params['page_id']; // 首页种类ID
        isset($params['industry']) && $goods_data['industry'] = $params['industry']; // 行业类别名称
        isset($params['caption']) && $goods_data['caption'] = $params['caption']; // 副标题
        isset($params['external_url']) && $goods_data['external_url'] = $params['external_url']; // 外网链接
        isset($params['store_clause']) && $goods_data['store_clause'] = $params['store_clause']; // 厂家条款

        // 保存GoodsContents表
        $goods_cxt_data = [];
        isset($params['weight']) && $goods_cxt_data['weight'] = (float)$params['weight']; // 商品净重
        isset($params['content']) && $goods_cxt_data['content'] = $params['content']; // 外网链接
        isset($params['tag']) && $goods_cxt_data['tag'] = json_encode($params['tag']); // 商品标签
        isset($params['unit']) && $goods_cxt_data['unit'] = $params['unit']; // 计量单位
        // 更新Goods表和GoodsContent表的数据
        $this->updateGoodsAndContent($id, $goods_data, $goods_cxt_data);
    }

    /**
     * 更新Goods表和GoodsContent表的数据
     * @param int $id 商品ID
     * @param array $goods_data goods表保存的数据
     * @param array $goods_cxt_data goods_contents表保存的数据
     */
    public function updateGoodsAndContent(int $id, array $goods_data, array $goods_cxt_data)
    {
        Db::beginTransaction();
        try {
            // Goods表更新
            $goods_result = $this->dao->update(['id' => $id], $goods_data);
            if (!$goods_result) throw new CustomException('GOODS.UPDATE_FAIL');
            // goods_contents表更新
            if (!empty($goods_cxt_data)) {
               $content_result = $this->goods_contents_dao->update(['goods_id' => $id], $goods_cxt_data);
                if (!$content_result) throw new CustomException('GOODS.UPDATE_FAIL');
            }
            Db::commit();
        } catch (CustomException $e) {
            Db::rollBack();
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            $this->error('COMMON.SYSTEM_ERROR');
        }
    }

    /**
     * 添加Goods表和GoodsContents表
     * @param array $params
     */
    public function createGoodsAndContentData(array $params)
    {
        $goods_data = [];
        // 保存Goods表
        $goods_data['category_id'] = (int)$params['category_id']; // 种类ID
        $goods_data['title'] = $params['title']; // 商品标题
        $goods_data['buy_type'] = (int)$params['buy_type']; // 购买方式
        $goods_data['picture'] = $params['picture']; // 封面图
        isset($params['banners']) && $goods_data['banners'] = json_encode($params['banners']); // 轮播图
        $goods_data['price'] = (float)$params['price']; // 商品价格
        $goods_data['original_price'] = (float)$params['original_price']; // 商品原价
        $goods_data['integral'] = (int)$params['integral']; // 积分
        isset($params['sort']) && $goods_data['sort'] = (int)$params['sort']; // 排序
        isset($params['page_id']) && $goods_data['page_id'] = (int)$params['page_id']; // 首页种类ID
        isset($params['industry']) && $goods_data['industry'] = $params['industry']; // 行业类别名称
        isset($params['caption']) && $goods_data['caption'] = $params['caption']; // 副标题
        isset($params['external_url']) && $goods_data['external_url'] = $params['external_url']; // 外网链接
        isset($params['store_clause']) && $goods_data['store_clause'] = $params['store_clause']; // 厂家条款
        $this->error('GOODS.CREATE_FAIL');
        Db::beginTransaction();
        try {
            // Goods表创建
            $goods_id = $this->dao->createGetId($goods_data);
            if (!$goods_id) throw new CustomException('GOODS.CREATE_FAIL');

            // 保存GoodsContents表
            $goods_cxt_data = [];
            isset($params['weight']) && $goods_cxt_data['weight'] = (float)$params['weight']; // 商品净重
            isset($params['content']) && $goods_cxt_data['content'] = $params['content']; // 外网链接
            isset($params['tag']) && $goods_cxt_data['tag'] = json_encode($params['tag']); // 商品标签
            isset($params['unit']) && $goods_cxt_data['unit'] = $params['unit']; // 计量单位
            $goods_cxt_data['goods_id'] = $goods_id;

            // goods_contents表更新
            if (!empty($goods_cxt_data)) {
                $content_result = $this->goods_contents_dao->create($goods_cxt_data);
                if (!$content_result) throw new CustomException('GOODS.CREATE_FAIL');
            }
            Db::commit();
        } catch (CustomException $e) {
            Db::rollBack();
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            $this->error('COMMON.SYSTEM_ERROR');
        }

    }

    /**
     * 拼接上级分类
     * @param array $cate_list
     * @return array
     */
    public function joinSuperCateData(array $cate_list)
    {
        $pids = array_unique(array_column($cate_list, 'pid'));

        $pid_names = $this->goods_category_dao->getGoodsCateByMap([
            'id' => ['in', $pids],
        ], null,['id', 'name'])->pluck('name', 'id')->toArray();

        foreach ($cate_list as &$item) {
            $item['create_time'] = date('Y-m-d',(int)$item['created_at']); // 创建时间
            $item['parent_name'] = $pid_names[$item['pid']]??'-'; // 父类分类名称
        }
        return $cate_list;
    }

}